package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuService")
@Slf4j
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuAttrValueService spuAttrValueService;  //注入service是为了使用saveBatch()批处理方法

    @Autowired
    private SpuDescMapper spuDescMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuAttrValueService skuAttrValueService;

    @Autowired
    private GmallSmsClient gmallSmsClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    /**
     * 分页条件查询
     *
     * @param paramVo
     * @param categoryId
     * @return
     */
    @Override
    public PageResultVo querySpuByPageAndCategoryId(PageParamVo paramVo, Long categoryId) {
        QueryWrapper<SpuEntity> wrapper = new QueryWrapper<>();
        if (categoryId != 0) {
            wrapper.eq("category_id", categoryId);
        }

        String key = paramVo.getKey();
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(t -> t.like("id", key).or().like("name", key));
        }

        IPage<SpuEntity> page = this.page(paramVo.getPage(), wrapper);

        return new PageResultVo(page);
    }

    @GlobalTransactional
    @Override
    public void bigSave(SpuVo spu) {
        //1.保存spu
        //1.1 保存spu信息
        Long spuId = saveSpuInfo(spu);

        //1.2 保存spu描述信息 pms_spu_desc
        saveSpuDesc(spu, spuId);

        //1.3 保存spu基本属性信息
        saveBaseAttr(spu, spuId);

        //2.保存sku
        //2.1 保存sku基本信息
        saveSkuInfo(spu, spuId);

        sendMessage(spuId, "insert");
    }

    private void sendMessage(Long id, String type) {
        //发送消息
        try {
            this.rabbitTemplate.convertAndSend("PMS_ITEM_EXCHANGE", "item." + type, id);
        } catch (Exception e) {
            log.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }

    }

    @Transactional
    public void saveSkuInfo(SpuVo spu, Long spuId) {
        List<SkuVo> skuVoList = spu.getSkus();
        if (CollectionUtils.isEmpty(skuVoList)) {
            return;
        }
        skuVoList.forEach(skuVo -> {
            SkuEntity skuEntity = new SkuEntity();
            BeanUtils.copyProperties(skuVo, skuEntity);

            skuEntity.setBrandId(spu.getBrandId());
            skuEntity.setCategoryId(spu.getCategoryId());

            //获取sku图片列表
            List<String> images = skuVo.getImages();
            if (!CollectionUtils.isEmpty(images)) {
                skuEntity.setDefaultImage(skuEntity.getDefaultImage() == null ? images.get(0) : skuEntity.getDefaultImage());
            }
            skuEntity.setSpuId(spuId);
            this.skuMapper.insert(skuEntity);
            //新增sku信息之后获取skuId
            Long skuId = skuEntity.getId();
            //2.1 保存sku图片信息 pms_sku_images
            if (!CollectionUtils.isEmpty(images)) {
                String defaultImage = images.get(0);
                this.skuImagesService.saveBatch(images.stream().map(image -> {
                    //封装skuImagesEntity对象
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultStatus(StringUtils.equals(defaultImage, image) ? 1 : 0);
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setSort(0);
                    skuImagesEntity.setUrl(image);

                    return skuImagesEntity;
                }).collect(Collectors.toList()));
            }
            //2.2 保存sku的销售属性信息
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();
            if (!CollectionUtils.isEmpty(saleAttrs)) {
                saleAttrs.forEach(saleAttr -> {
                    saleAttr.setSort(0);
                    saleAttr.setSkuId(skuId);
                });
                this.skuAttrValueService.saveBatch(saleAttrs);
            }

            //远程调用sms服务接口，插入营销相关的信息
            SkuSaleVo skuSaleVo = new SkuSaleVo();
            BeanUtils.copyProperties(skuVo, skuSaleVo);
            skuSaleVo.setSkuId(skuId);
            this.gmallSmsClient.saveSkuSaleInfo(skuSaleVo);

        });
    }

    @Transactional
    public void saveBaseAttr(SpuVo spu, Long spuId) {
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)) {
            //批量插入
            spuAttrValueService.saveBatch(baseAttrs.stream().map(spuAttrValueVo -> {

                SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
                //将SpuAttrValueVo对象转换为spuAttrValueEntity
                BeanUtils.copyProperties(spuAttrValueVo, spuAttrValueEntity);
                spuAttrValueEntity.setSpuId(spuId);
                spuAttrValueEntity.setSort(0);  //随便设置的sort的值，也可以不设置

                return spuAttrValueEntity;
            }).collect(Collectors.toList()));
        }
    }

    @Transactional
    public void saveSpuDesc(SpuVo spu, Long spuId) {
        SpuDescEntity spuDescEntity = new SpuDescEntity();
        // 注意：spu_info_desc表的主键是spu_id,需要在实体类中配置该主键不是自增主键
        spuDescEntity.setSpuId(spuId);
        // 把商品的图片描述，保存到spu详情中，图片地址以逗号进行分割
        spuDescEntity.setDecript(StringUtils.join(spu.getSpuImages(), ","));
        this.spuDescMapper.insert(spuDescEntity);
    }


    @Transactional
    public Long saveSpuInfo(SpuVo spu) {
        spu.setPublishStatus(1);  //默认已上架
        spu.setCreateTime(new Date());
        spu.setUpdateTime(spu.getCreateTime());
        this.spuMapper.insert(spu);
        //获取新增后的spuId
        Long spuId = spu.getId();
        return spuId;
    }

}